
package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.constant.CacheConstants;
import com.qk.vo.portal.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Slf4j
@SuppressWarnings("all")
public class RedisAspect {
    @Autowired
    private StringRedisTemplate redisClient;

    @Pointcut("@annotation(com.qk.management.aop.anno.Cacheable)")
    public void pt(){}
    @Around("pt()")
    public Object redisCache(ProceedingJoinPoint pjp){
        String redisKey = "";
//        long expireTime = 0L;
//        TimeUnit expireTimeUnit = null;
        Object result;
        try{
            //pjp还可用于获取注解及注解中的属性
/*            Class<?> targetClass = pjp.getTarget().getClass();
            Method method = targetClass.getMethod(methodName);
            Cacheable annotation = method.getAnnotation(Cacheable.class); // 获取注解
            expireTime = annotation.expireTime();
            expireTimeUnit = annotation.expireTimeUnit();*/
            String methodName = pjp.getSignature().getName();
            redisKey = CacheConstants.CACHE_PORTAL_KEY_PREFIX + methodName;
            String jsonStr = redisClient.opsForValue().get(redisKey);
            if(ObjectUtil.isNotEmpty(jsonStr)){
                result = JSONUtil.toBean(jsonStr, PortalVO.class);
                log.info("从Redis取得数据");
                return result;
            }
        }catch (Exception e){
            log.error("redis查询异常", e);
        }
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            result = Result.error("您的操作有问题，稍后重试！");
            //原方法出现异常后直接返回，不再执行缓存逻辑
            return result;
        }
        if(ObjectUtil.isEmpty( result)|| ObjectUtil.isEmpty(redisKey)) return result;
        try {
            redisClient.opsForValue().set(redisKey,JSONUtil.toJsonStr(result),60*5, TimeUnit.SECONDS);
            log.info("添加缓存");
        } catch (Exception e) {
            log.info("redis添加缓存异常", e);
        }
        return result;
    }

}